﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Data;
using System.Data.Common;
using ProcessControl.Entity;
using MyLib;

namespace ProcessControl.Logic
{
    public class ApprovalHistoryLogic
    {
        private DataHelper db = new DataHelper();
        string flag = DataHelper.ParameterFlag;
        public DataTable GetApprovalHistoryByProc(string ProcessaName, int Incident)
        {
            try
            {
                StringBuilder strsql = new StringBuilder();
                strsql.Append("select t.*,substr(t.approver,instr2('/',t.approver)+1,length(t.approver)) as UserName from WF_ApprovalHistory t where ProcessName=" + flag + "ProcessName and Incident=" + flag + "Incident order by APPROVEDATE");
                DbCommand dbcom = db.GetSqlStringCommond(strsql.ToString());
                db.AddInParameter(dbcom, "" + flag + "ProcessName", DbType.String, ProcessaName);
                db.AddInParameter(dbcom, "" + flag + "Incident", DbType.Int32, Incident);
                return db.ExecuteDataTable(dbcom);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public List<ApprovalHistoryEntity> GetApprovalHistory(string ProcessaName, int Incident)
        {
            try
            {
                StringBuilder strsql = new StringBuilder();
                strsql.Append("select * from WF_ApprovalHistory where ProcessName=" + flag + "ProcessName and Incident=" + flag + "Incident order by id");
                DbCommand dbcom = db.GetSqlStringCommond(strsql.ToString());
                db.AddInParameter(dbcom, "" + flag + "ProcessName", DbType.String, ProcessaName);
                db.AddInParameter(dbcom, "" + flag + "Incident", DbType.Int32, Incident);
                DbDataReader dr = db.ExecuteReader(dbcom);
                List<ApprovalHistoryEntity> list = new List<ApprovalHistoryEntity>();
                while (dr.Read())
                {
                    ApprovalHistoryEntity item = new ApprovalHistoryEntity();
                    if (dr["ID"] != null && !String.IsNullOrEmpty(dr["ID"].ToString()))
                    {
                        item.ID = dr["ID"].ToString();
                    }
                    if (dr["ProcessName"] != null && !String.IsNullOrEmpty(dr["ProcessName"].ToString()))
                    {
                        item.ProcessName = dr["ProcessName"].ToString();
                    }
                    if (dr["Incident"] != null && !String.IsNullOrEmpty(dr["Incident"].ToString()))
                    {
                        try
                        {
                            item.Incident = Convert.ToInt32(dr["Incident"].ToString());
                        }
                        catch
                        {
                            item.Incident = 0;
                        }
                    }
                    if (dr["STEPLEVEL"] != null && !String.IsNullOrEmpty(dr["STEPLEVEL"].ToString()))
                    {
                        item.Level = dr["STEPLEVEL"].ToString();
                    }
                    if (dr["StepName"] != null && !String.IsNullOrEmpty(dr["StepName"].ToString()))
                    {
                        item.StepName = dr["StepName"].ToString();
                    }
                    if (dr["Approver"] != null && !String.IsNullOrEmpty(dr["Approver"].ToString()))
                    {
                        item.Approver = dr["Approver"].ToString();
                    }
                    if (dr["ApproverFrom"] != null && !String.IsNullOrEmpty(dr["ApproverFrom"].ToString()))
                    {
                        item.ApproverFrom = dr["ApproverFrom"].ToString();
                    }
                    if (dr["Action"] != null && !String.IsNullOrEmpty(dr["Action"].ToString()))
                    {
                        item.Action = dr["Action"].ToString();
                    }
                    if (dr["Comments"] != null && !String.IsNullOrEmpty(dr["Comments"].ToString()))
                    {
                        item.Comments = dr["Comments"].ToString();
                    }
                    if (dr["ApproveDate"] != null && !String.IsNullOrEmpty(dr["ApproveDate"].ToString()))
                    {
                        try
                        {
                            item.ApproveDate = Convert.ToDateTime(dr["ApproveDate"].ToString());
                        }
                        catch { }
                    }
                    if (dr["Status"] != null && !String.IsNullOrEmpty(dr["Status"].ToString()))
                    {
                        item.Status = dr["Status"].ToString();
                    }
                    if (dr["Ext01"] != null && !String.IsNullOrEmpty(dr["Ext01"].ToString()))
                    {
                        item.Ext01 = dr["Ext01"].ToString();
                    }
                    if (dr["Ext02"] != null && !String.IsNullOrEmpty(dr["Ext02"].ToString()))
                    {
                        item.Ext02 = dr["Ext02"].ToString();
                    }
                    if (dr["Ext03"] != null && !String.IsNullOrEmpty(dr["Ext03"].ToString()))
                    {
                        item.Ext03 = dr["Ext03"].ToString();
                    }
                    if (dr["Ext04"] != null && !String.IsNullOrEmpty(dr["Ext04"].ToString()))
                    {
                        item.Ext04 = dr["Ext04"].ToString();
                    }
                    if (dr["Ext05"] != null && !String.IsNullOrEmpty(dr["Ext05"].ToString()))
                    {
                        item.Ext05 = dr["Ext05"].ToString();
                    }
                    list.Add(item);
                }
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public ApprovalHistoryEntity GetApprovalHistoryByID(string ID)
        {
            try
            {
                StringBuilder strsql = new StringBuilder();
                strsql.Append("select * from WF_ApprovalHistory where ID=" + flag + "ID order by id");
                DbCommand dbcom = db.GetSqlStringCommond(strsql.ToString());
                db.AddInParameter(dbcom, "" + flag + "ID", DbType.Int32, ID);
                DbDataReader dr = db.ExecuteReader(dbcom);
                ApprovalHistoryEntity item = new ApprovalHistoryEntity();
                while (dr.Read())
                {
                    if (dr["ID"] != null && !String.IsNullOrEmpty(dr["ID"].ToString()))
                    {
                        item.ID = dr["ID"].ToString();
                    }
                    if (dr["ProcessName"] != null && !String.IsNullOrEmpty(dr["ProcessName"].ToString()))
                    {
                        item.ProcessName = dr["ProcessName"].ToString();
                    }
                    if (dr["Incident"] != null && !String.IsNullOrEmpty(dr["Incident"].ToString()))
                    {
                        try
                        {
                            item.Incident = Convert.ToInt32(dr["Incident"].ToString());
                        }
                        catch
                        {
                            item.Incident = 0;
                        }
                    }
                    if (dr["StepName"] != null && !String.IsNullOrEmpty(dr["StepName"].ToString()))
                    {
                        item.StepName = dr["StepName"].ToString();
                    }
                    if (dr["STEPLEVEL"] != null && !String.IsNullOrEmpty(dr["STEPLEVEL"].ToString()))
                    {
                        item.Level = dr["STEPLEVEL"].ToString();
                    }
                    if (dr["Approver"] != null && !String.IsNullOrEmpty(dr["Approver"].ToString()))
                    {
                        item.Approver = dr["Approver"].ToString();
                    }
                    if (dr["ApproverFrom"] != null && !String.IsNullOrEmpty(dr["ApproverFrom"].ToString()))
                    {
                        item.ApproverFrom = dr["ApproverFrom"].ToString();
                    }
                    if (dr["Action"] != null && !String.IsNullOrEmpty(dr["Action"].ToString()))
                    {
                        item.Action = dr["Action"].ToString();
                    }
                    if (dr["Comments"] != null && !String.IsNullOrEmpty(dr["Comments"].ToString()))
                    {
                        item.Comments = dr["Comments"].ToString();
                    }
                    if (dr["ApproveDate"] != null && !String.IsNullOrEmpty(dr["ApproveDate"].ToString()))
                    {
                        try
                        {
                            item.ApproveDate = Convert.ToDateTime(dr["ApproveDate"].ToString());
                        }
                        catch { }
                    }
                    if (dr["Status"] != null && !String.IsNullOrEmpty(dr["Status"].ToString()))
                    {
                        item.Status = dr["Status"].ToString();
                    }
                    if (dr["Ext01"] != null && !String.IsNullOrEmpty(dr["Ext01"].ToString()))
                    {
                        item.Ext01 = dr["Ext01"].ToString();
                    }
                    if (dr["Ext02"] != null && !String.IsNullOrEmpty(dr["Ext02"].ToString()))
                    {
                        item.Ext02 = dr["Ext02"].ToString();
                    }
                    if (dr["Ext03"] != null && !String.IsNullOrEmpty(dr["Ext03"].ToString()))
                    {
                        item.Ext03 = dr["Ext03"].ToString();
                    }
                    if (dr["Ext04"] != null && !String.IsNullOrEmpty(dr["Ext04"].ToString()))
                    {
                        item.Ext04 = dr["Ext04"].ToString();
                    }
                    if (dr["Ext05"] != null && !String.IsNullOrEmpty(dr["Ext05"].ToString()))
                    {
                        item.Ext05 = dr["Ext05"].ToString();
                    }
                }
                return item;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public bool AddApprovalHistory(IDbTransaction trans, ApprovalHistoryEntity Item)
        {
            try
            {
                StringBuilder strsql = new StringBuilder();
                strsql.Append("INSERT INTO WF_ApprovalHistory (Id,ProcessName,Incident,StepName,STEPLEVEL,Approver,ApproverFrom,Action,Comments,ApproveDate,Status,Ext01,Ext02,Ext03,Ext04,Ext05)");
                strsql.Append(" VALUES ");
                strsql.Append("(" + flag + "Id," + flag + "ProcessName," + flag + "Incident," + flag + "StepName," + flag + "STEPLEVEL," + flag + "Approver," + flag + "ApproverFrom," + flag + "Action," + flag + "Comments," + flag + "ApproveDate," + flag + "Status," + flag + "Ext01," + flag + "Ext02," + flag + "Ext03," + flag + "Ext04," + flag + "Ext05)");
                //IDbCommand cmd = trans.Connection.CreateCommand();
                IDbCommand cmd = DataAccess.Instance("BizDB").GetDbCommand();
                DbCommand dbcom = cmd as DbCommand;
                //dbcom.Transaction = (DbTransaction)trans;
                dbcom.CommandText = strsql.ToString();
                db.AddInParameter(dbcom, "" + flag + "Id", DbType.String, Guid.NewGuid().ToString());
                db.AddInParameter(dbcom, "" + flag + "ProcessName", DbType.String, Item.ProcessName);
                db.AddInParameter(dbcom, "" + flag + "Incident", DbType.Int32, Item.Incident);
                db.AddInParameter(dbcom, "" + flag + "StepName", DbType.String, Item.StepName);
                db.AddInParameter(dbcom, "" + flag + "STEPLEVEL", DbType.String, Item.Level);
                db.AddInParameter(dbcom, "" + flag + "Approver", DbType.String, Item.Approver);
                db.AddInParameter(dbcom, "" + flag + "ApproverFrom", DbType.String, Item.ApproverFrom);
                db.AddInParameter(dbcom, "" + flag + "Action", DbType.String, Item.Action);
                db.AddInParameter(dbcom, "" + flag + "Comments", DbType.String, Item.Comments);
                db.AddInParameter(dbcom, "" + flag + "ApproveDate", DbType.DateTime, Item.ApproveDate);
                db.AddInParameter(dbcom, "" + flag + "Status", DbType.String, Item.Status);
                db.AddInParameter(dbcom, "" + flag + "Ext01", DbType.String, Item.Ext01);
                db.AddInParameter(dbcom, "" + flag + "Ext02", DbType.String, Item.Ext02);
                db.AddInParameter(dbcom, "" + flag + "Ext03", DbType.String, Item.Ext03);
                db.AddInParameter(dbcom, "" + flag + "Ext04", DbType.String, Item.Ext04);
                db.AddInParameter(dbcom, "" + flag + "Ext05", DbType.String, Item.Ext05);

                foreach (DbParameter param in dbcom.Parameters)
                {
                    if (param.Value == null)
                    {
                        param.Value = DBNull.Value;
                    }
                }
                if (dbcom.Connection.State == ConnectionState.Closed)
                {
                    dbcom.Connection.Open();
                }
                dbcom.ExecuteNonQuery();

                dbcom.Connection.Close();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public bool DeleteApprovalHistoryByID(string ID)
        {
            try
            {
                StringBuilder strsql = new StringBuilder();
                if (ID.IndexOf(",") > 0)
                {
                    strsql.Append("delete from WF_ApprovalHistory where ID in(" + ID + ")");
                }
                else
                {
                    strsql.Append("delete from WF_ApprovalHistory where ID ='" + ID + "'");
                }
                if (db.ExecuteNonQuery(strsql.ToString()) > 0)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 根据流程名，主体，一级中心或智能部门，二级部门返回相应的财务审批人员
        /// </summary>
        /// <param name="strProcessname">流程名</param>
        /// <param name="strCompany">主体</param>
        /// <param name="CenterDept">一级中心或智能部门</param>
        /// <param name="subDeptID">二级部门ID</param>
        /// <param name="strError">报错信息</param>
        /// <param name="FinanceUserID">财务审批人员</param>
        /// <param name="Cashier">出纳</param>
        public void GetFinancePerson(string strProcessname, string strCompany, string CenterDept, string subDeptID, ref string FinanceUserID, ref string Cashier)
        {
            IDataReader Reader = null;
            //OleDbConnection oleConnection = null;
            // strError = "";
            try
            {
                if (CenterDept.Contains("["))
                {
                    CenterDept = CenterDept.Split(new char[] { '[' })[0];
                }
                //1.1 根据主体 部门返回出纳
                switch (strCompany)
                {
                    case "新疆金风科技股份有限公司":
                        if (CenterDept == "服务中心[1005069]" && (subDeptID == "10003830" || subDeptID == "1005080"))
                        {
                            Cashier = "ULTIMUS/24349";
                        }
                        else
                        {
                            Cashier = "ULTIMUS/24661";
                        }
                        break;
                    case "北京金风科创风电设备有限公司":
                        Cashier = "ULTIMUS/23863";
                        break;
                    case "北京天源科创风电技术有限责任公司":
                        Cashier = "ULTIMUS/24652";
                        break;

                    default:
                        Cashier = "SYSTEMUSER";
                        break;
                }
                if (strCompany == "北京博风慧能软件有限责任公司")
                {
                    FinanceUserID = "ULTIMUS/9196";
                    Cashier = "ULTIMUS/24652";
                }
                else
                {
                    //1.2 取数据库中的财务人员
                    string strQuery = " select t.financeuserid, nvl(t.subdeptid,' ') as subdeptid from WF_FINANCEPERSON t where  " +
                        " t.isenable=1 and t.company='" + strCompany + "' and t.centerdept='" + CenterDept + "' ";
                    //  db.
                    //if (helper.GetTotalRows(strQuery) < 0)
                    //{
                    //    strError = "未找到相关财务任务！";
                    //    helper.AppendTextToLog(DateTime.Now.ToShortTimeString() + " ==调用GetFinancePerson:" + strError);
                    //    FinanceUserID = "SYSTEMUSER";
                    //    return;
                    //}
                    DataTable dt = db.ExecuteDataTable(strQuery);
                    DataRow[] drs = dt.Select("SUBDEPTID like '%" + subDeptID + "%'");
                    if (dt.Rows.Count <= 0)
                    {
                        FinanceUserID = "SYSTEMUSER";
                        return;
                    }
                    if (drs.Length > 0)
                    {
                        FinanceUserID = drs[0][0].ToString();
                    }
                    else
                    {

                        drs = dt.Select("SUBDEPTID=' '");
                        if (drs.Length > 0)
                            FinanceUserID = drs[0][0].ToString();
                        else
                            FinanceUserID = "SYSTEMUSER";
                    }

                }
            }
            catch (Exception ex)
            {
                FinanceUserID = "SYSTEMUSER";
                throw ex;
            }
        }
        public bool DeleteApprovalHistoryByProc(string ProcessaName, int Incident)
        {
            try
            {
                StringBuilder strsql = new StringBuilder();
                strsql.Append("delete from WF_ApprovalHistory where ProcessName=" + flag + "ProcessName and Incident=" + flag + "Incident");
                DbCommand dbcom = db.GetSqlStringCommond(strsql.ToString());
                db.AddInParameter(dbcom, "" + flag + "ProcessName", DbType.String, ProcessaName);
                db.AddInParameter(dbcom, "" + flag + "Incident", DbType.Int32, Incident);
                if (db.ExecuteNonQuery(dbcom) > 0)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}